package rush.edu.wechat.common.service.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import rush.edu.wechat.common.service.db.DbConfig;

import javax.sql.DataSource;

/**
 * DESC:配置新闻的数据库
 * USER:hmily
 * DATE:2018/1/31
 * TIME:10:39
 */
public class DefaultMybatisConfig implements MybatisConfig {

    @Primary
    @Bean(name = "dataSource")
    @Override
    public DataSource dataSource(DbConfig dbConfig) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        dataSource.setDriverClassName(dbConfig.getDriverClass());
        dataSource.setUsername(dbConfig.getUsername());
        dataSource.setPassword(dbConfig.getPassword());
        dataSource.setUrl(dbConfig.getUrl());
        dataSource.setDbType(dbConfig.getDbType());
        return dataSource;
    }


    @Bean(name = "sqlSessionFactory")
    @Override
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource,GlobalConfiguration globalConfiguration,DbConfig dbConfig) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDialectType(dbConfig.getDialectType());
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        factoryBean.setPlugins(new Interceptor[]{paginationInterceptor});
        factoryBean.setGlobalConfig(globalConfiguration);
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(dbConfig.getMapperLocation()));
        return factoryBean.getObject();
    }

    @Bean(name = "globalConfiguration")
    public GlobalConfiguration devGlobalConfiguration(DbConfig dbConfig ){
        GlobalConfiguration globalConfiguration =  new GlobalConfiguration();
        globalConfiguration.setDbColumnUnderline(dbConfig.getColumnUnderline());
        globalConfiguration.setDbType(dbConfig.getDbType());
        globalConfiguration.setIdType(dbConfig.getIdType());
        return globalConfiguration;
    }

    @Bean(name = "sqlSessionTemplate")
    @Override
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
